let express = require('express');
const User = require('../schemas/users');
const Comment = require('../schemas/comment');
const Content = require('../schemas/content');
const router = express.Router();

// 统一返回格式
let responseData;
router.use(function(req, res, next){
  responseData = {
    code: 0,
    message: ''
  }
  next();
})

// 注册接口
router.post('/user/register', async function(req, res, next){
  const { username, password, repassword } = req.body;
  if(username === ''){
    responseData.code = 1;
    responseData.message = '用户名不能为空';
    res.json(responseData);
    return;
  }
  if(password === ''){
    responseData.code = 2;
    responseData.message = '密码不能为空';
    res.json(responseData);
    return;
  }
  if(password != repassword){
    responseData.code = 3;
    responseData.message = '两次密码不一致';
    res.json(responseData);
    return;
  }

  let userInfo = await User.findOne({ where: { username: username } });
  if(userInfo){
    // 说明存在
    responseData.code = 4;
    responseData.message = '该用户名已存在！';
    res.json(responseData);
  }else{
    // 不存在该用户名，存数据库
    responseData.message = '注册成功';

    let user = {
      username,
      password
    }
    const jane = await User.create(user);
    res.json(responseData);
  }
  /*
  let userRe = typeorm.getConnection().getRepository(User);
  // 查询数据库中是否存在该用户名
  userRe.find({ username: username }).then(function(userInfo){
    console.log(userInfo);
    if(userInfo){
      // 说明存在
      responseData.code = 4;
      responseData.message = '该用户名已存在！';
      res.json(responseData);
    }else{
      // 不存在该用户名，存数据库
      responseData.message = '注册成功';

      let user = {
        username,
        password
      }
      userRe.save(user).then(function(savePost){
        console.log(savePost);
      });
      res.json(responseData);
    }
  });
  */
})
// 登录接口
router.post('/user/login', async function(req, res, next){
  // 获取前端提交的用户名和密码
  const { username, password } = req.body;
  if(username == '' || password == ''){
    responseData.code = 1;
    responseData.message = '用户名和密码不能为空';
    res.json(responseData);
    return;
  }
  // 查询数据库中是否有相同的用户名和密码
  let resInfo = await User.findOne({ 
    where: { 
      username: username,
      password: password
    } 
  });
  if(resInfo){ //说明输入正确，能从数据库中查到
    responseData.message = "登录成功！";
    responseData.userInfo = {
      id: resInfo.id,
      username: resInfo.username
    };
    req.cookies.set('userInfo', JSON.stringify({
      id: resInfo.id,
      username: resInfo.username,
      isAdmin: resInfo.isAdmin
    }));

    res.json(responseData);
  }else{ //说明账户名或者密码不对
    responseData.code = 5;
    res.setHeader("over-line-error", 44);
    res.sendStatus(401)
    responseData.message = "账户名或密码不正确！";
    res.json(responseData);
  }
  /*
  // 查询数据库中是否有相同的用户名和密码
  let userRe = typeorm.getConnection().getRepository(User);
  userRe.findOne({
    username: username,
    password: password
  }).then(function(resInfo){
    console.log(resInfo)
    if(resInfo){//说明输入正确，能从数据库中查到
      responseData.message = "登录成功！";
      responseData.userInfo = {
        id: resInfo.id,
        username: resInfo.username
      };
      req.cookies.set('userInfo', JSON.stringify({
        id: resInfo.id,
        username: resInfo.username
      }));
      res.json(responseData);
    }else{//说明账户名或者密码不对
      responseData.code = 5;
      responseData.message = "账户名或密码不正确！";
      res.json(responseData);
    }
  });
  */
});
// 退出接口
router.get('/user/logout', function(req, res, next){
  req.cookies.set('userInfo', null);
  res.json(responseData);
})
// 评论的提交
router.post('/comment/post', async function(req, res){
  let { content, contentId } = req.body;
  let userId = req.userInfo.id;

  // 创建一条评论
  console.log(req.body);
  let singleComment = await Comment.create({
    detail: content,
    userId: Number(userId),
    contentId: Number(contentId)
  });
  // 评论成功后，需要拉该内容的所有评价
  let comments = await Comment.findAll({
    where: {
      contentId: contentId
    },
    include: [User, Content]
  });
  responseData.message = '评论成功！';
  responseData.data = {
    comments: comments
  }
  res.json(responseData);
});
// 获取comment
router.get('/comment', async function(req, res){
  let contentId = req.query.contentId || '';

  // 从数据库中去查找该内容下的所有评论信息
  let comments = await Comment.findAll({
    where: {
      contentId: contentId
    },
    include: [User, Content]
  });
  responseData.data = comments;
  res.json(responseData);
});
module.exports = router;